package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsManagerInfoMapper;
import cc.rengu.igas.bsps.common.dao.EventInfoMapper;
import cc.rengu.igas.bsps.common.dao.EventLogMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsManagerInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.EventInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.EventLogMapperImpl;
import cc.rengu.igas.bsps.common.entity.EventInfo;
import cc.rengu.igas.bsps.common.entity.EventLog;
import cc.rengu.igas.bsps.common.entity.ManagerInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.BankManagerService;
import cc.rengu.igas.bsps.facade.request.EventProcessRequest;
import cc.rengu.igas.bsps.facade.response.EventProcessResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;

/**
 * 工单信息管理服务
 * Created by 王成 on 2018/10/26.
 *
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/07
 */
public class EventProcessService extends BankManagerService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        EventProcessRequest eventProcessRequest = new EventProcessRequest();
        ConvertUtil.convertOutput(eventProcessRequest);
        return eventProcessRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        EventProcessRequest eventProcessRequest = (EventProcessRequest) request;
        /*获取请求参数相关信息：法人行，用户标识，事件ID，拓展经理工号，处理状态和处理结果*/
        String instId = eventProcessRequest.getHeader().getInstId();
        String userId = eventProcessRequest.getUserId();
        String eventId = eventProcessRequest.getEventId();
        String managerId = eventProcessRequest.getManagerId();
        String eventStatus = eventProcessRequest.getEventStatus();
        String eventProcResult = eventProcessRequest.getEventProcResult();
        /* 参数合法性校验 */
        if (StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(eventId) || StringUtil.isEmptyOrNull(eventStatus)
                || StringUtil.isEmptyOrNull(eventProcResult) || StringUtil.isEmptyOrNull(managerId)) {
            rglog.error("用户标识<{}>，事件编号<{}>，处理结果<{}>，处理状态<{}>，拓展经理工号<{}>不能为空!", userId,
                    eventId, eventProcessRequest.getEventProcResult(), eventStatus);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /* 获取工单申报信息 */
        EventInfoMapper eventInfoMapper = new EventInfoMapperImpl();
        EventInfo eventInfo = eventInfoMapper.selectEventInfoByPrimaryKey(instId, eventProcessRequest.getEventId());
        if (null == eventInfo) {
            rglog.error("根据工单编号<{}>获取工单申报信息失败!", eventProcessRequest.getEventId());
            throw new BizException(RespCodeEnum.QUERY_EVENT_INFO_ERROR.getRespCode(), RespCodeEnum.QUERY_EVENT_INFO_ERROR.getRespDesc());
        }
        /*查询当前登录人（拓展经理）手机号*/
        String managerPhone = "";
        //根据用户编号查询拓展经理工号
        BspsManagerInfoMapper managerInfoMapper = new BspsManagerInfoMapperImpl();
        ManagerInfo managerInfo = null;
        if ("APP".equals(eventProcessRequest.getHeader().getChanlId())){
            managerInfo = managerInfoMapper.selectBspsManagerInfoById(instId,userId);
        }else {
            managerInfo = managerInfoMapper.selectBspsManagerInfoByOpenId(instId, userId);
        }
        if (null == managerInfo) {
            rglog.error("拓展经理不存在<{}>", userId);
            throw new BizException(RespCodeEnum.GET_USER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_INFO_ERROR.getRespDesc());
        }
        managerPhone = managerInfo.getManagerPhone();
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        /* 登记事件操作日志 */
        EventLogMapper eventLogMapper = new EventLogMapperImpl();
        EventLog eventLog = new EventLog();
        eventLog.setInstId(eventInfo.getInstId());
        eventLog.setEventId(eventInfo.getEventId());
        eventLog.setEventStatus(eventProcessRequest.getEventStatus());
        eventLog.setEventProcDesc(eventProcessRequest.getEventProcResult());
        eventLog.setPreOprId(eventInfo.getCurrentProcUser());
        eventLog.setPreOprDate(DateUtil.getCurrentDate());
        eventLog.setPreOprTime(DateUtil.getCurrentTime());
        eventLog.setOprId(eventProcessRequest.getManagerId());
        eventLog.setOprDate(DateUtil.getCurrentDate());
        eventLog.setOprTime(DateUtil.getCurrentTime());
        int iReturnCode = eventLogMapper.insertEventLogInfo(eventLog);
        if (0 != iReturnCode) {
            rglog.error("登记事件标识<{}>操作日志信息失败，iReturnCode:<{}>", eventInfo.getEventId(), iReturnCode);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }

        /* 更新事件申报信息 */
        eventInfo.setCurrentProcUser(managerInfo.getManagerId());
        eventInfo.setCurrentProcPhone(managerPhone);
        eventInfo.setLastProcTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        eventInfo.setEventStatus(eventStatus);
        eventInfo.setEventProcResult(eventProcResult);
        iReturnCode = eventInfoMapper.updateEventInfoByPrimaryKey(eventInfo);
        if (0 != iReturnCode) {
            rglog.error("根据事件标识<{}>更新事件申报信息失败，iReturnCode:<{}>", eventInfo.getEventId(), iReturnCode);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
        /* 结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);
        /* 组装应答报文 */
        EventProcessResponse eventProcessResponse = new EventProcessResponse();
        BizResponse<EventProcessResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(eventProcessResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        EventProcessResponse eventProcessResponse = (EventProcessResponse) bizResponse.getResult();
        ConvertUtil.convertInput(eventProcessResponse);
    }
}
